<template>
  <div v-if="currentPage" :style="globalStyles" class="wid-hei-inherit">
    <global-share-components v-if="isDisplaySharePage" :class="{isHidePage: true}"></global-share-components>
    <div :id="'page-' + (pageIndex+1)" :style="siteStyles_">
      <div :style="pageStyles_" class="page">
        <group-component :item="currentPage" :pageId="pageIndex+1" class="wid-hei-inherit"></group-component>
      </div>
    </div>
    <div v-if="siteAttrs.isDisplayDebuggerText" class="version"> {{ version }} </div>
  </div>
</template>
<script>
import { EventBus } from '@/store/index'
import { COMPONENT_TYPES } from '@/common/const'
import { H5_TYPE, MOBILE_WID_HEI } from '@/common/const-dif'
import { commonUtils } from '@/components/utils/common-utils'
import { pageTemplate } from '@/components/utils/page-template'
import { wbBase } from '@/components/utils/wbBase'
import { pageAnimate } from '@/others/pages/js/page-animate'
import { pageLoading } from '@/others/pages/js/page-loading'
import { pageCommon } from '@/others/pages/js/page-common'
import { pageScrollTrigger } from '@/others/pages/js/page-scroll-trigger'
import { defineAsyncComponent, reactive } from 'vue'
import { getPxOVwByValue } from '@/store/utils'
import { searchComponentDataByCid } from '@/store/index-utils'
import { getCompIdByParam } from '@/plugins/utils'
import { LIST_TYPE_MAP } from '@/common/const-items'

const components = {
  GroupComponent: defineAsyncComponent(() => import('@/components/group-component.vue')),
  GlobalShareComponents: defineAsyncComponent(() => import("@/others/pages/global-share-components.vue")),
};

export default {
  mixins: [commonUtils, pageTemplate, pageAnimate, pageLoading, pageCommon, wbBase, pageScrollTrigger],
  setup () {
    const state = reactive({
      version: '版本v4.1',
      isHidePage: true,
      currentPage: null,
    })
    const state_ = {
      isOpenEventPop: true,
      oldPageId: -1,
      H5_TYPE: H5_TYPE,
      commonLists: [],
    }
    _.merge(state, state_)
    return state
  },
  components,
  created() {
    EventBus.$off("showPage", this.showLoading)
    EventBus.$on("showPage", this.showLoading)
    EventBus.$off("showPageNoneLoading", this.showPageById)
    EventBus.$on("showPageNoneLoading", this.showPageById)
    EventBus.$off("recoverPageBg", this.onRecoverPageBg)
    EventBus.$on("recoverPageBg", this.onRecoverPageBg)

    EventBus.$off("displayDebuggerInfo", this.onDisplayDebuggerInfo)
    EventBus.$on("displayDebuggerInfo", this.onDisplayDebuggerInfo)
    EventBus.$off("adjustPageHeight", this.onAdjustPageHeight)
    EventBus.$on("adjustPageHeight", this.onAdjustPageHeight)
  },
  mounted() {
    if(this.isMountLoading){
      if(this.pages && this.pageIndex >= 0 && this.pages[this.pageIndex]) {
        this.showLoading({ pageId: this.pageIndex+1 });
      }
    }
  },
  computed: {
    isDisplaySharePage(){
      return _.size(this.isGlobalShareComponents) > 0 ? true : false;
    },
    globalStyles() {
      let styles_ = {}
      styles_.width = this.currentPage.styles.width
      styles_.height = this.currentPage.styles.height
      styles_.overflow = "hidden"
      return styles_
    },
    siteStyles_() {
      let styles_ = this.siteStyles
      styles_.width = this.currentPage.styles.width
      styles_.height = this.currentPage.styles.height
      return styles_
    },
    pageStyles_() {
      return this.currentPage.styles
    },
    getSiteBgUrl(){
      let url = this.siteStyles.backgroundImage
      let url_ = url.match(/\((\S*)\)/)
      return url_[1] ? url_[1] : ''
    },
    pageId(){
      return this.pageIndex + 1;
    }
  },
  methods: {
    onAdjustPageHeight(groupCompId) {
      const dom = document.getElementById(groupCompId)
      const groupCompData= this.componentMap[groupCompId]
      if(dom) {
        const bottomHeight = (this.currentPage.attrs.height - groupCompData.conAttr.top - groupCompData.conAttr.height)
        let pageHeight = dom.offsetHeight + (groupCompData.conAttr.top + bottomHeight)/MOBILE_WID_HEI.adaptiveScale
        if(pageHeight < MOBILE_WID_HEI.clientHeight) {
          pageHeight = MOBILE_WID_HEI.clientHeight
        }
        this.$store.commit('updatePageAttr', { id: this.currentPage.id, styles: { height: (pageHeight + 'px') } });
        const compId = getCompIdByParam(groupCompData.commonAttr.heightCompId)
        if(compId) {
          const compData = this.componentMap[compId]
          const reallyHeight = pageHeight*MOBILE_WID_HEI.adaptiveScale
          const top = reallyHeight - bottomHeight + compData.conAttr.height/2
          const conStyles =  { top: getPxOVwByValue(top) }
          this.$store.commit('updateComponentAttr', { id: compId, conStyles });
        }
      }
    },
    onDisplayDebuggerInfo({text}){
      this.version = text;
    },
    onRecoverPageBg(){
      this.$store.commit('updatePageAttr', { id: this.currentPage.id, styles: {backgroundImage:'url(' + this.currentPage.attrs.bgUrl+ ')'} });
    },
    showLoading({ pageId }) {
      this.isMountLoading = false
      this.currentPage = this.pages[pageId - 1];
      // this.setPageImgTotal()
      //加入当前页面有通用列表且开启自动调整组件高度的功能，那么就调用这个方法
      if(this.frontData.pageCommonListAutoHeight[this.currentPage.id]){
        this.adjustListTopAndPageHeight()
      }
      this.pageInitEvents()

      this.eventPostAddLoading({ pageId })
      document.documentElement.scrollTop = 0
      this.$nextTick(() => {
        //弹层动画自动播放
        const pageId_ = 'page-' + pageId;
        const currentPageDom = document.getElementById(pageId_);
        this.initPlayAllAnimates(currentPageDom);
      })
    },
    showPageById({ pageId }) {
      if (this.oldPageId != pageId) {
        this.isOpenEventPop = true
      }
      this.$nextTick(() => {
        this.isFixIosForm();

        this.oldPageId = pageId;

        this.isForbidMove(true);

        //长页滚动触发打组之间中的组件动画集
        this.startScrollTRigger();
      })

      this.autoTriggerEvent();
      if(this.currentPage.isAdjustPageHeight) {
        const groupCompData = searchComponentDataByCid(COMPONENT_TYPES.group_carousel, this.currentPage)
        if(groupCompData && groupCompData.commonAttr.listType == LIST_TYPE_MAP.relative) {
          this.setIntervalCb = window.setInterval(() => {
            const dom = document.getElementById(groupCompData.id)
            if(dom) {
              window.clearInterval(this.setIntervalCb)
              this.onAdjustPageHeight(groupCompData.id)
            }
          }, this.siteInfo.reloadTime)
        }
      }
    },
    adjustListTopAndPageHeight(){
      EventBus.$off('adjustListTopAndPageHeight', this.adjustListTopAndPageHeight);
      while(this.commonLists.length > 0){
        this.commonLists.pop();
      }
      _.forEach(this.currentPage.components, (componentData) => {
        if(componentData.cid == COMPONENT_TYPES.wb_common_list && componentData.commonAttr.isAutoY){
          this.commonLists.push(componentData);
        }
      })
      if(this.commonLists.length > 0){
        EventBus.$on('adjustListTopAndPageHeight', this.adjustListTopAndPageHeight)

        this.commonLists = _.sortBy(this.commonLists, (componentData) => { return componentData.conAttr.top; });
        let curHeight = 0;
        let curTop = 0;
        _.forEach(this.commonLists, (componentData, index) => {
          if(componentData.conAttr.height_){
            curHeight += componentData.conAttr.height_
          }else{
            curHeight += componentData.conAttr.height;
          }
          if(index > 0){
            let preComponentData = this.commonLists[index-1];
            if(!componentData.conAttr.hasOwnProperty('gap')){
              let gap = componentData.conAttr.top - (preComponentData.conAttr.top + preComponentData.conAttr.height)
              componentData.conAttr.gap = parseInt(gap);
            }else{
              let top = componentData.conAttr.gap + preComponentData.conAttr.top + preComponentData.conAttr.height;
              top = parseInt(top);
              this.$store.commit('updateComponentAttr', {id:componentData.id, conStyles:{top:getPxOVwByValue(top)}});
            }
          }else{
            curTop = componentData.conAttr.top
          }
        })
        let pageHeight = curHeight + curTop;
        // 更新页面的高度
        this.$store.commit('updatePageAttr', { id: this.currentPage.id, styles: { height: getPxOVwByValue(pageHeight) } });
      }
    }
  },
  beforeUnmount(){
    EventBus.$on("showPage", this.showLoading)
    EventBus.$off("showPageNoneLoading", this.showPageById)
    EventBus.$off("adjustPageHeight", this.onAdjustPageHeight)
  }
};
</script>
